/**
 * @(#)UserAgentServiceImpl.java 2017年4月8日
 * Copyright(C) 2017 ZHEXIN IT CO.,LTD. All rights reserved.
 */
package org.jsbd.boss.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.jsbd.boss.common.redis.RedisClient;
import org.jsbd.boss.dao.IBrowserDAO;
import org.jsbd.boss.dao.IUserAgentDAO;
import org.jsbd.boss.domian.channel.BrowserVo;
import org.jsbd.boss.domian.channel.UserAgent;
import org.jsbd.boss.service.IUserAgentService;
import org.jsbd.boss.util.CacheKey;
import org.jsbd.boss.util.DateUtil;
import org.jsbd.boss.util.NumUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;

import edu.hziee.cap.common.util.Md5Utils;
import edu.hziee.common.queue.DelayExecuteBuffer;

/**
 * useragent收集
 * 
 * @author <a href="mailto:xupengcheng@zhexinit.com" >徐鹏程</a>
 * @version 1.0.0
 */
@Service
public class UserAgentServiceImpl implements IUserAgentService {
	public static final Logger LOGGER = LoggerFactory.getLogger(UserAgentServiceImpl.class);
	@Resource
	private IUserAgentDAO userAgentDAO;

	@Resource(name = "userAgentBuffer")
	private DelayExecuteBuffer<UserAgent> userAgentBuffer;

	@Resource
	private CacheParamManager cacheParamManager;
	@Resource
	private RedisClient redisClient;

	@Resource
	private IBrowserDAO browserDAO;

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.jsbd.boss.service.IUserAgentService#collectionUserAgent()
	 */
	@Override
	public void collectionUserAgent(String day) {
		List<String> agentList = null;// channelEventLogDAO.getUserAgent(day);
		for (int i = 0; i < agentList.size(); i++) {
			String agent = agentList.get(i);
			UserAgent userAgent = new UserAgent();
			try {
				// 如果是数组的话去掉
				JSONArray.parseArray(agent);
			} catch (Exception e) {
				userAgent.setUserAgent(agent);
				userAgent.setAgentMd5(Md5Utils.getMd5(agent));
				userAgentBuffer.add(userAgent);
				if (i % 100 == 0) {
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e1) {
					}
				}
			}
		}
	}

	@Override
	public List<String> selectUserAgentList(int length) {
		List<String> list = new ArrayList<String>();
		List<BrowserVo> browserList = new ArrayList<BrowserVo>();
		List<Double> rateList = new ArrayList<Double>();
		Object browserObj = redisClient.get(CacheKey.BROWSER_LIST);
		boolean flag = false;
		if (browserObj == null) {
			browserList = browserDAO.selectBrowserList();
			redisClient.put(CacheKey.BROWSER_LIST, browserList, 600);
		} else {
			browserList = (List<BrowserVo>) browserObj;
		}
		for (BrowserVo browserVo : browserList) {
			rateList.add(browserVo.getRate());
		}
		if (browserList != null && browserList.size() > 0) {
			List<String> browerList = new ArrayList<String>();
			for (int i = 0; i < length; i++) {
				int index = NumUtil.randomChoiceIndex(rateList.toArray(new Double[0]));
				if (index < 0) {
					index = 0;
				}
				String code = browserList.get(index).getCode();
				if ("firefox".equals(code)) {
					flag = true;
				}
				browerList.add(code);
			}
			Object userAgentObj = redisClient.get(CacheKey.USER_AGENT_LIST);
			List<BrowserVo> browserVoList = new ArrayList<BrowserVo>();
			if (userAgentObj == null) {
				// 查询
				browserVoList = browserDAO.selectBrowserVersionList();
				redisClient.put(CacheKey.USER_AGENT_LIST, browserVoList, 600);
			} else {
				browserVoList = (List<BrowserVo>) userAgentObj;
			}
			Map<String, List<BrowserVo>> map = new HashMap<String, List<BrowserVo>>();
			for (BrowserVo browserVo : browserVoList) {
				String browserCode = browserVo.getCode();
				List<BrowserVo> tempList = map.get(browserCode);
				if (tempList == null) {
					tempList = new ArrayList<BrowserVo>();
				}
				tempList.add(browserVo);
				map.put(browserCode, tempList);
			}

			// 从useragent 查询useragent前缀
			List<UserAgent> userAgentList = userAgentDAO.selectUserAgentList(length);
			for (int i = 0; i < userAgentList.size(); i++) {
				UserAgent userAgent = userAgentList.get(i);
				String userAgentPre = userAgent.getUserAgent();
				int index = userAgentPre.lastIndexOf(")") + 1;
				userAgentPre = userAgentPre.substring(0, index);
				List<BrowserVo> tempBrowserList = map.get(browerList.get(i));
				if (tempBrowserList != null) {
					int browserVersionIndex = (int) (Math.random() * tempBrowserList.size());
					String userAgentEnd = tempBrowserList.get(browserVersionIndex).getVersion();
					list.add(userAgentPre + " " + userAgentEnd);
				}
			}
			if (flag) {
				list.add("Mozilla/5.0 (Android 6.0.1; Mobile; rv:53.0) Gecko/53.0 Firefox/53.0");
			}
		}
		return list;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.jsbd.boss.service.IUserAgentService#collectionUserAgent()
	 */
	@Override
	public void collectionUserAgent() {
		Set<String> days = DateUtil.getDatesBetweenTwoDate("20160901", DateUtil.getCurrentDateStr());
		for (String day : days) {
			if (redisClient.evalSetNx(CacheKey.USER_AGENT_COLLECT_LOCK + day, 86400)) {
				Object collectionFlag = null;//cacheParamManager.getParamValue(CacheKey.USETAGENT_FLAG);
				if (collectionFlag != null && collectionFlag.equals("1")) {
					LOGGER.info("useragent执行更新{}对应的数据", day);
					collectionUserAgent(day);
				}
			}
		}
	}
}
